(function(window,$){


  function Player(opts){
    if(!(this instanceof Player)){
      return new Player(opts)
    }

    this.context = new AudioContext();

    this.fftSize = opts.fftSize || 2048;

    this.source = null;
    this.gainNode = this.context.createGain();
    this.filterNode = this.context.createBiquadFilter();
    this.filterNode.type = "allpass";
    this.analyserNode = this.context.createAnalyser();

    this.dataArray = null;
    this.vid = null;
    this.waveDataCallback = opts.dataCallback;


    this.waveData = function(){
      // this.analyserNode.getByteTimeDomainData(this.dataArray);
      this.analyserNode.getByteFrequencyData(this.dataArray);
      this.waveDataCallback(this.dataArray);
      this.vid = window.requestAnimationFrame(this.waveData.bind(this));
    }
     
  }

  Player.prototype.stop = function(){
    this.source.stop(2);
    // this.source.buffer = null;
    window.cancelAnimationFrame(this.vid);
  };

  Player.prototype.volume = function(value){
    this.gainNode.gain.value = value;
  };

  Player.prototype.filter = function(name){
    this.filterNode.type = name;
  };

  Player.prototype.addFile = function(data,callback){
    this.context.decodeAudioData(data, function (b) {
      this.source = this.context.createBufferSource();
      this.source.buffer = b;
      this.source.connect(this.gainNode);
      this.gainNode.connect(this.filterNode);
      this.filterNode.connect(this.analyserNode);
      this.analyserNode.fftSize = this.fftSize;
      this.dataArray = new Uint8Array(this.analyserNode.frequencyBinCount);
      this.analyserNode.connect(this.context.destination); 
      callback();   
    }.bind(this));
  };

  Player.prototype.playLocal = function (){
    this.source.start();

    this.waveData();
  };

  Player.prototype.play = function (data){
    var _buff = null;
    var request = new XMLHttpRequest();
    request.open('GET', data, true);
    request.responseType = 'arraybuffer';
    request.onload = function () {
        this.context.decodeAudioData(request.response, function (b) {

        console.info('play...')
        this.source = this.context.createBufferSource();
        this.source.buffer = b;
        this.source.connect(this.gainNode);
        this.gainNode.connect(this.filterNode);
        this.filterNode.connect(this.analyserNode);
        this.analyserNode.fftSize = this.fftSize;
        this.dataArray = new Uint8Array(this.analyserNode.frequencyBinCount);
        this.analyserNode.connect(this.context.destination);
        this.source.start();

        this.waveData();
      }.bind(this), function(e){
        console.log(e);
      });
    }.bind(this)
    request.send();  

    


  };


  window.Player = Player;





})(window,jQuery);
